﻿using RabbitMQ.Client;

namespace LS.Screening.UI.Common
{
    public abstract class MQConfig<T> : FileConfig<T>
        where T : MQConfig<T>, new()
    {
        /// <summary>
        /// 是否启用MQ来替换内置Messager
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 服务器地址
        /// </summary>
        [Crypto]
        public string Host { get; set; }

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// 用户
        /// </summary>
        [Crypto]
        public string User { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        [Crypto]
        public string Password { get; set; }

        /// <summary>
        /// 交换机名称，默认为系统名称
        /// </summary>
        public string ExchangeName { get; set; }

        private static ConnectionFactory factory;
        private static object lockObj = new object();

        /// <summary>
        /// 获取单个RabbitMQ连接
        /// </summary>
        /// <param name="Heartbeat">客户端心跳同步秒数，默认为60秒</param>
        /// <returns></returns>
        public static IConnection GetConnection(int Heartbeat = 60)
        {
            if (factory == null)
            {
                lock (lockObj)
                {
                    factory = new ConnectionFactory
                    {
                        HostName = Instance.Host,//ip
                        Port = Instance.Port,//端口
                        UserName = Instance.User,//账号
                        Password = Instance.Password,//密码
                    };
                }
            }
            factory.RequestedHeartbeat = TimeSpan.FromSeconds(Heartbeat);
            return factory.CreateConnection();
        }

        protected override void OnCreated()
        {
            base.OnCreated();
            if (string.IsNullOrEmpty(Host))
            {
                Host = "192.168.0.34";
                Port = 5672;
                User = "admin";
                Password = "admin@123";
                ExchangeName = AppConfig.Instance.SystemCode;
            }
        }
    }

    /// <summary>
    /// PubSubMQ配置
    /// </summary>
    public class PubSubMQConfig : MQConfig<PubSubMQConfig>
    {

    }
}
